package NO6_Tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 2025-08-18
 * 广度搜索一般方法
 */
public class BFSMain {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(
                3,
                new TreeNode(9),
                new TreeNode(20, new TreeNode(15), new TreeNode(7)));
        levelOrderBFS(root);
    }

    // 广度优先搜索（层级遍历）
    public static void levelOrderBFS(TreeNode root) {
        if (root == null) return;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            int levelSize = queue.size();
            for (int i = 0; i < levelSize; i++) {
                TreeNode node = queue.poll();
                System.out.print(node.val + " ");

                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            System.out.println(); // 换行表示不同层级
        }
    }
}
